package com.zhudi.advice;

import com.zhudi.annotation.AuthCheck;
import com.zhudi.expection.BusinessException;
import com.zhudi.model.emun.AuthEnum;
import com.zhudi.model.entity.User;
import com.zhudi.service.UserService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.util.Objects;

import static com.zhudi.commen.ErrorCode.NOT_LOGIN;
import static com.zhudi.commen.ErrorCode.NO_AUTH;
import static com.zhudi.contant.UserContant.ADMIN;
import static com.zhudi.contant.UserContant.USER_LOGIN_STATE;

@Component
@Aspect
/**
 * 用于身份检查的切面类
 */
public class PermissionAdvice {

    @Resource
    private UserService userService;


    /**
     * 检查是否登录的切面
     */
    @Before("@annotation(com.zhudi.annotation.UserLoginCheck)")
    public void UserLoginCheck(JoinPoint joinPoint){
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
        if (servletRequestAttributes==null){
            throw new BusinessException(NOT_LOGIN);
        }
        HttpServletRequest request = servletRequestAttributes.getRequest();
        Object loginUser = request.getSession().getAttribute(USER_LOGIN_STATE);
        if (loginUser==null){
            throw new BusinessException(NOT_LOGIN);
        }

    }

    /**
     * 检查是否登录的切面
     */
    @Before("@annotation(authCheck)")
    public void AuthCheck(JoinPoint joinPoint, AuthCheck authCheck){
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
        if (servletRequestAttributes==null){
            throw new BusinessException(NO_AUTH);
        }
        HttpServletRequest request = servletRequestAttributes.getRequest();
        User loginUser = (User) request.getSession().getAttribute(USER_LOGIN_STATE);
        if (loginUser==null){
            throw new BusinessException(NO_AUTH);
        }
        //根据注解拿到对应的权限
        String role = authCheck.role().toUpperCase();

        //这里添加一步将字母都转为大写
        //根据String得到对应的是什么role
        AuthEnum roleEnum = AuthEnum.getSatus(role);
        //判断用户是否有这个权限

        if(!Objects.equals(roleEnum.getValue(), loginUser.getRole())){
            throw new BusinessException(NO_AUTH);
        }


    }


}
